<?php

namespace Tests;

use Hyn\Tenancy\Models\Hostname;
use Hyn\Tenancy\Models\Website;
use Hyn\Tenancy\Repositories\HostnameRepository;
use Hyn\Tenancy\Repositories\WebsiteRepository;
use Illuminate\Support\Facades\Artisan;

trait MigrateFreshSeedOnce
{
    /**
     * If true, setup has run at least once.
     * @var boolean
     */
    protected static $setUpHasRunOnce = false;


    private function createTestSite()
    {
        $fqdn = config('app.url');
        $fqdn = mb_ereg_replace('http:\/\/|https:\/\/', '', $fqdn);
        $WEBSITE_UUID = mb_ereg_replace('\.|-', '_', $fqdn);
        $website = Website::where('uuid', $WEBSITE_UUID)->count();
        if (empty($website)) {
            $website = new Website();
            $website->uuid = $WEBSITE_UUID;
            app(WebsiteRepository::class)->create($website);
            $hostname = new Hostname;
            $hostname->fqdn = $fqdn;
            $hostname = app(HostnameRepository::class)->create($hostname);
            app(HostnameRepository::class)->attach($hostname, $website);
        }
        $out = Artisan::call("tenancy:migrate:refresh");
        $out = Artisan::call("tenancy:db:seed");
        echo Artisan::output();
    }

    /**
     * After the first run of setUp "migrate:fresh --seed"
     * @return void
     */
    public function setUp(): void
    {
        parent::setUp();
        if (!static::$setUpHasRunOnce) {
//            $output = shell_exec('php artisan migrate:refresh --database=tenancy_test');
            $this->createTestSite();
//            $out = Artisan::call("tenancy:migrate:refresh", ["--database" => "tenancy_test"]);
//            $out = Artisan::call("tenancy:db:seed");
//            echo Artisan::output();
//            $this->artisan("migrate:refresh --database=sqlite_testing");
//            $this->artisan("db:seed");
//            Artisan::call('migrate:fresh');
//            Artisan::call(
//                'db:seed', ['--class' => 'DatabaseSeeder']
//            );
            static::$setUpHasRunOnce = true;
        }
    }
}
